package xyz.zq.sf.common.mybatis;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import xyz.zq.sf.common.mybatis.handler.SqlFilterArgumentResolver;

import java.util.List;

/**
 * mybatis 配置
 *
 * @author hzq
 * @date 2021-01-28 11:57
 */
@Configuration(proxyBeanMethods = false)
@RequiredArgsConstructor
public class MyBatisAutoConfiguration implements WebMvcConfigurer {

    private final TenantLineHandler tenantLineHandler;

    /**
     * 添加参数解析器
     *
     * @param resolvers 处理程序方法参数解析器
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        // 添加 mybatis 分页 page 参数解析器 防止sql注入
        resolvers.add(new SqlFilterArgumentResolver());
    }

    /**
     * 先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //多租户
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(tenantLineHandler));
        //分页 对于单一数据库类型来说,都建议配置该值,避免每次分页都去抓取数据库类型
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        //乐观锁
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

}
